import React from 'react';
import {Header, List, Form, Segment, Button} from 'semantic-ui-react'
import Cookie from 'react-cookies'
import EVTools from "../utils/evtools";
import axios from "axios";

class TokenManage extends React.Component {

    constructor(props){
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        this.setState({
            token: event.target.value
        });
    }

    componentWillMount() {
        this.setState({
            token: Cookie.load('Token'),
            username: Cookie.load('Username'),
            tokenValid: Cookie.load('Token') !== undefined
        })
    }

    submit = (e, data)=>{
        if (typeof(this.state.token)!=="string" || this.state.token === "") {
            alert("Token 不能为空！")
            return
        }
        let infoUrl = "https://gitee.com/api/v5/user?access_token=" + this.state.token
        let mainThis = this
        axios.get(infoUrl)
            .then(function (response) {
                Cookie.save('Token', mainThis.state.token);
                Cookie.save('Username', response.data.login);
                mainThis.setState({
                    username: response.data.login,
                    tokenValid: true,
                })
                EVTools.emit("Username", Cookie.load('Username'))
                alert("你好 " + mainThis.state.username + "，授权成功!")
            })
            .catch(function () {
                alert("Token 验证失败，请确认后重试！");
            });
    };

    cancel = (e, data)=>{
        Cookie.remove('Token');
        Cookie.remove('Username');
        this.setState({
            token: "",
            tokenValid: Cookie.load('Token') !== undefined,
            username: Cookie.load('Username')
        })
        EVTools.emit("Username", undefined)
        alert("清除授权成功！")
    };

    render() {
        return(
            <div id={"token"}>
                <Header as='h1'>Gitee 授权管理</Header>
                <Segment>
                    <List bulleted>
                        <List.Item>
                            您需要先在 Gitee 生成一个私人公钥，生成地址：
                            <a
                                href={"https://gitee.com/profile/personal_access_tokens"}
                                target={"_blank"}
                            >
                                https://gitee.com/profile/personal_access_tokens
                            </a>
                        </List.Item>
                        <List.Item>
                            生成后添加到下方表单即可，如需清除授权，只需要点击撤销即可。
                        </List.Item>
                        <List.Item>
                            需要注意的是，撤销后方可重新授权
                        </List.Item>
                    </List>
                </Segment>

                <Form>
                    <Form.Field>
                        <label>
                            Gitee 私人 Token（已授权 Gitee 用户
                            <span className="authored">
                                {typeof(this.state.username) === 'string' ? this.state.username : "无"}
                            </span>
                            ）
                        </label>
                        <input
                            placeholder='token here'
                            value={this.state.token || ''}
                            onChange={this.handleChange}
                            disabled={this.state.tokenValid}
                        />
                    </Form.Field>
                    <Button
                        type='submit'
                        color={"orange"}
                        onClick={this.submit.bind(this)}
                        disabled={this.state.tokenValid}
                    >
                        授权
                    </Button>
                    <Button
                        type='submit'
                        color={"red"}
                        onClick={this.cancel.bind(this)}
                        disabled={!this.state.tokenValid}
                    >
                        撤销
                    </Button>
                </Form>
            </div>
        )
    }
}

export default TokenManage